unit UFrameStock;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
  Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
  cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit,
  cxMaskEdit, cxButtonEdit;

type
  TFrameStock = class(TFrame)
    edtStock: TcxButtonEdit;
    procedure edtStockExit(Sender: TObject);
    procedure edtStockPropertiesButtonClick(Sender: TObject;
      AButtonIndex: Integer);
    procedure edtStockKeyPress(Sender: TObject; var Key: Char);
  private
    procedure SetNullData;
    procedure SetSelectData;
    procedure ShowStockSelect(ClearFilter: Boolean);
  public
    gStockGuid: string;
  end;

implementation

uses UDmBillBase, UFrmStockSelect;

{$R *.dfm}

procedure TFrameStock.edtStockKeyPress(Sender: TObject; var Key: Char);
var
  lStock: string;
begin
  if Key = #13 then
  begin
    lStock := Trim(edtStock.Text);
    if lStock = '' then
      ShowStockSelect(True)
    else
      edtStockExit(Sender);
  end;
end;

procedure TFrameStock.edtStockPropertiesButtonClick(Sender: TObject;
  AButtonIndex: Integer);
begin
  ShowStockSelect(True);
end;

procedure TFrameStock.SetNullData;
begin
  gStockGuid := '';
  edtStock.Text := '';
end;

procedure TFrameStock.SetSelectData;
begin
  gStockGuid := DmBillBase.CdsStock.FindField('Guid').AsString;
  edtStock.Text := DmBillBase.CdsStock.FindField('StockName').AsString;
end;

procedure TFrameStock.edtStockExit(Sender: TObject);
var
  lStock: string;
begin
  lStock := Trim(edtStock.Text);
  if lStock = '' then
  begin
    SetNullData;
    Exit;
  end;
  DmBillBase.DoStockFilter(lStock);
  if DmBillBase.CdsStock.RecordCount = 1 then
  begin
    SetSelectData;
  end
  else
  if DmBillBase.CdsStock.RecordCount > 1 then
  begin
    ShowStockSelect(False);
  end
  else
  begin
    SetNullData;
  end;
  DmBillBase.CdsStock.Filtered := False;
  DmBillBase.CdsStock.Filter := '';
end;

procedure TFrameStock.ShowStockSelect(ClearFilter: Boolean);
begin
  if ClearFilter then
  begin
    DmBillBase.CdsStock.Filtered := False;
    DmBillBase.CdsStock.Filter := '';
  end;
  FrmStockSelect := TFrmStockSelect.Create(nil);
  try
    if FrmStockSelect.ShowModal = mrOk then
    begin
      SetSelectData;
    end
    else
    begin
      SetNullData;
    end;
  finally
    FreeAndNil(FrmStockSelect);
  end;
end;

end.
